<template>
  <div class="write-guide-page">
    <div class="container">
      <!-- 头部 -->
      <div class="page-header">
        <h1 class="page-title">写攻略</h1>
        <div class="header-actions">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" :loading="saving" @click="handleSave">
            发布攻略
          </el-button>
        </div>
      </div>

      <!-- 表单 -->
      <div class="write-form">
        <!-- 标题 -->
        <div class="form-item">
          <label class="form-label">攻略标题</label>
          <el-input
            v-model="form.title"
            placeholder="给你的攻略起个吸引人的标题吧"
            maxlength="100"
            show-word-limit
            size="large"
          />
        </div>

        <!-- 封面图 -->
        <div class="form-item">
          <label class="form-label">封面图片</label>
          <el-upload
            class="cover-uploader"
            action="#"
            :show-file-list="false"
            :before-upload="handleCoverUpload"
            accept="image/*"
          >
            <img v-if="form.cover" :src="form.cover" class="cover-image" />
            <div v-else class="upload-placeholder">
              <el-icon class="upload-icon"><Plus /></el-icon>
              <div class="upload-text">上传封面图</div>
            </div>
          </el-upload>
          <div class="form-tip">建议尺寸：1200x600，支持 JPG、PNG 格式</div>
        </div>

        <!-- 分类 -->
        <div class="form-item">
          <label class="form-label">攻略分类</label>
          <el-select v-model="form.category" placeholder="选择分类" size="large">
            <el-option label="美食" value="food" />
            <el-option label="住宿" value="hotel" />
            <el-option label="交通" value="transport" />
            <el-option label="路线" value="route" />
            <el-option label="实用贴士" value="tips" />
          </el-select>
        </div>

        <!-- 标签 -->
        <div class="form-item">
          <label class="form-label">标签</label>
          <div class="tags-input">
            <el-tag
              v-for="tag in form.tags"
              :key="tag"
              closable
              @close="handleRemoveTag(tag)"
              class="tag-item"
            >
              {{ tag }}
            </el-tag>
            <el-input
              v-if="tagInputVisible"
              ref="tagInputRef"
              v-model="tagInputValue"
              size="small"
              class="tag-input"
              @keyup.enter="handleAddTag"
              @blur="handleAddTag"
            />
            <el-button
              v-else
              size="small"
              @click="showTagInput"
              class="add-tag-btn"
            >
              + 添加标签
            </el-button>
          </div>
          <div class="form-tip">最多添加5个标签</div>
        </div>

        <!-- 富文本编辑器 -->
        <div class="form-item">
          <label class="form-label">攻略内容</label>
          <div class="editor-wrapper">
            <div ref="editorRef" class="editor-container"></div>
          </div>
          <div class="form-tip">
            提示：可以插入图片、视频，使用标题、列表等格式让内容更清晰
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { createEditor, createToolbar } from '@wangeditor/editor'
import '@wangeditor/editor/dist/css/style.css'
// import { createGuide, uploadImage } from '@/api/travel/index.js'

const router = useRouter()

const saving = ref(false)
const editorRef = ref(null)
const tagInputRef = ref(null)
const tagInputVisible = ref(false)
const tagInputValue = ref('')

let editor = null

// 表单数据
const form = ref({
  title: '',
  cover: '',
  category: '',
  tags: [],
  content: ''
})

// 初始化编辑器
const initEditor = () => {
  if (!editorRef.value) return

  // 编辑器配置
  const editorConfig = {
    placeholder: '开始写你的攻略吧...',
    MENU_CONF: {
      uploadImage: {
        // 自定义上传图片
        async customUpload(file, insertFn) {
          try {
            // TODO: 调用上传接口
            // const res = await uploadImage(file)
            // insertFn(res.data.url, res.data.alt, res.data.href)
            
            // 模拟上传
            const url = URL.createObjectURL(file)
            insertFn(url, file.name, url)
            ElMessage.success('图片上传成功')
          } catch (error) {
            ElMessage.error('图片上传失败')
          }
        }
      }
    }
  }

  // 创建编辑器
  editor = createEditor({
    selector: editorRef.value,
    config: editorConfig,
    mode: 'default'
  })

  // 工具栏配置
  const toolbarConfig = {
    toolbarKeys: [
      'headerSelect',
      'bold',
      'italic',
      'underline',
      '|',
      'color',
      'bgColor',
      '|',
      'bulletedList',
      'numberedList',
      '|',
      'uploadImage',
      'insertLink',
      'blockquote',
      'codeBlock',
      '|',
      'undo',
      'redo'
    ]
  }

  // 创建工具栏
  createToolbar({
    editor,
    selector: editorRef.value,
    config: toolbarConfig,
    mode: 'default'
  })
}

// 上传封面
const handleCoverUpload = (file) => {
  // TODO: 调用上传接口
  // const res = await uploadImage(file)
  // form.value.cover = res.data.url
  
  // 模拟上传
  form.value.cover = URL.createObjectURL(file)
  ElMessage.success('封面上传成功')
  return false
}

// 显示标签输入框
const showTagInput = () => {
  if (form.value.tags.length >= 5) {
    ElMessage.warning('最多添加5个标签')
    return
  }
  tagInputVisible.value = true
  nextTick(() => {
    tagInputRef.value?.focus()
  })
}

// 添加标签
const handleAddTag = () => {
  const tag = tagInputValue.value.trim()
  if (tag && !form.value.tags.includes(tag)) {
    if (form.value.tags.length >= 5) {
      ElMessage.warning('最多添加5个标签')
    } else {
      form.value.tags.push(tag)
    }
  }
  tagInputVisible.value = false
  tagInputValue.value = ''
}

// 移除标签
const handleRemoveTag = (tag) => {
  form.value.tags = form.value.tags.filter(t => t !== tag)
}

// 取消
const handleCancel = () => {
  ElMessageBox.confirm('确定要取消吗？未保存的内容将丢失', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '继续编辑',
    type: 'warning'
  }).then(() => {
    router.back()
  }).catch(() => {})
}

// 保存
const handleSave = async () => {
  // 表单验证
  if (!form.value.title.trim()) {
    ElMessage.warning('请输入攻略标题')
    return
  }
  if (!form.value.cover) {
    ElMessage.warning('请上传封面图片')
    return
  }
  if (!form.value.category) {
    ElMessage.warning('请选择攻略分类')
    return
  }

  // 获取编辑器内容
  const content = editor.getHtml()
  if (!content || content === '<p><br></p>') {
    ElMessage.warning('请输入攻略内容')
    return
  }

  saving.value = true
  try {
    // TODO: 调用API
    // await createGuide({
    //   ...form.value,
    //   content: content
    // })
    
    // 模拟保存
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('攻略发布成功！')
    router.push('/guides')
  } catch (error) {
    ElMessage.error('发布失败，请重试')
  } finally {
    saving.value = false
  }
}

onMounted(() => {
  initEditor()
})

onBeforeUnmount(() => {
  if (editor) {
    editor.destroy()
  }
})
</script>

<style scoped lang="less">
.write-guide-page {
  min-height: 100vh;
  background: #f5f7fa;
  padding: 32px 0 80px;
}

.container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 0 24px;
}

// 页面头部
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32px;
  padding: 24px 32px;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
}

.page-title {
  font-size: 24px;
  font-weight: 700;
  color: #1a1a1a;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 12px;
}

// 表单
.write-form {
  background: #fff;
  border-radius: 16px;
  padding: 32px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
}

.form-item {
  margin-bottom: 32px;

  &:last-child {
    margin-bottom: 0;
  }
}

.form-label {
  display: block;
  font-size: 16px;
  font-weight: 600;
  color: #1a1a1a;
  margin-bottom: 12px;
}

.form-tip {
  font-size: 13px;
  color: #999;
  margin-top: 8px;
}

// 封面上传
.cover-uploader {
  :deep(.el-upload) {
    width: 100%;
    height: 300px;
    border: 2px dashed #ddd;
    border-radius: 12px;
    cursor: pointer;
    overflow: hidden;
    transition: all 0.3s;

    &:hover {
      border-color: #ff6b6b;
    }
  }
}

.cover-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #999;

  .upload-icon {
    font-size: 48px;
    margin-bottom: 12px;
  }

  .upload-text {
    font-size: 14px;
  }
}

// 标签输入
.tags-input {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

.tag-item {
  font-size: 14px;
}

.tag-input {
  width: 120px;
}

.add-tag-btn {
  border-style: dashed;
}

// 编辑器
.editor-wrapper {
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  overflow: hidden;
}

.editor-container {
  min-height: 500px;

  :deep(.w-e-text-container) {
    min-height: 500px;
  }

  :deep(.w-e-toolbar) {
    border-bottom: 1px solid #e8e8e8;
    background: #fafafa;
  }
}

// 响应式
@media (max-width: 768px) {
  .write-guide-page {
    padding: 20px 0 60px;
  }

  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
    padding: 20px;
  }

  .header-actions {
    width: 100%;

    .el-button {
      flex: 1;
    }
  }

  .write-form {
    padding: 24px 20px;
  }

  .cover-uploader {
    :deep(.el-upload) {
      height: 200px;
    }
  }

  .editor-container {
    min-height: 400px;

    :deep(.w-e-text-container) {
      min-height: 400px;
    }
  }
}
</style>
